package heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 带心跳检测的服务器
 */
public class HeartbeatServer {

    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(2);
        EventLoopGroup workerGroup = new NioEventLoopGroup(10);
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,100)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new StringDecoder())
                                                    .addLast(new StringEncoder())
                                                    //添加心跳检测处理器 3s读超时
                                                    .addLast(new IdleStateHandler(3,0,0, TimeUnit.SECONDS))
                                                    .addLast(new HeartbeatHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * 心跳处理器
     */
    static class HeartbeatHandler extends SimpleChannelInboundHandler<String>{

        //超时计数器
        static int count = 0;

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println(ctx.channel().remoteAddress()+"客户端连接了");
        }

        @Override
        protected void channelRead0(ChannelHandlerContext cxt, String s) throws Exception {
            System.out.println(cxt.channel().remoteAddress()+"客户端消息：" + s + ",时间：" + LocalDateTime.now());
        }

        //发生超时调用
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            IdleStateEvent event = (IdleStateEvent) evt;
            //判断超时事件类型如果是读超时
            if(event.state() == IdleState.READER_IDLE){
                count++;
                System.out.println("客户端发生了读超时事件：" + count);
                if(count > 3){
                    //执行异常处理逻辑
                    System.out.println("客户端心跳异常超过3次，关闭客户端连接");
                    ctx.close();
                    count = 0;
                }
            }
        }
    }
}
